<template>
	<view class="city">
		<text v-if="!hasError" class="text hover" @click="clicklocationRegion">{{locationRegion.name}}</text>
		<text v-else class="text">定位失败</text>
		<u-loading v-if="busy" mode="circle"></u-loading>
		<u-icon v-else name="reload" @click="position"></u-icon>
	</view>
</template>

<script>
	import {
		getNeareastCity
	} from "@/api/platform/user.js"
	export default {
		data() {
			return {
				locationRegion: undefined,
				busy: false,
				hasError: false
			};
		},
		mounted() {
			this.position()
		},
		methods: {
			clicklocationRegion() {
				this.$emit('location-region', this.locationRegion)
			},
			async getPosition() {
				let [err, loc] = await uni.getLocation({
				  type: "gcj02"
				})
				if (err) {
					console.error(err);
					this.busy = false
					this.hasError = true
					this.$emit('failed', err)
					return
				}
				try {
					this.locationRegion = await getNeareastCity({
						userLocation: {
							longitude: loc.longitude,
							latitude: loc.latitude
						}
					})
					this.$emit('success', this.locationRegion)
					this.busy = false
				} catch (e) {
					this.busy = false
					this.hasError = true
					this.$emit('failed', e)
					throw e
				}
			},
			async position() {
				if (this.busy) return
				this.busy = true
				this.hasError = false
				// 请求权限
				let that = this
				if (uni.authorize) {
					uni.authorize({
						scope: 'scope.userLocation',
						success() { // 有位置权限
							that.getPosition()
						},
						fail() { // 无位置权限
							uni.showModal({
								content: '检测到您没打开位置权限，是否去设置打开？',
								confirmText: '确认',
								cancelText: '取消',
								success(res) {
									if (res.cancel) {
										that.busy = false
										that.hasError = true
									}
									if (res.confirm) {
										uni.openSetting({
											success() {
												that.getPosition()
											}
										});
									}
								},
								fail(err) {
									console.log(err);
								}
							})
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.city {
		display: flex;
		align-items: center;
	}
	.text {
		min-width: 162rpx;
		height: 56rpx;
		line-height: 56rpx;
		text-align: center;
		border: 1px solid #ECECEC;
		border-radius: 32rpx;
		background-color: #ECECEC;
		padding: 0rpx 50rpx;
		margin-right: 20rpx;
	}
	.hover:hover {
		background-color: #bdbdbd;
	}
</style>
